package com.ruoyi.generator.util;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ydx
 * @date 2019-02-22 15:38
 */
@Component
public class DBUtils {


    @Value("${spring.datasource.druid.master.url}")
    private String masterUrl;

    @Value("${spring.datasource.druid.master.username}")
    private String username;

    @Value("${spring.datasource.druid.master.password}")
    private String password;



//    private static String simplify = masterUrl.substring(masterUrl.indexOf("//") + 2, masterUrl.indexOf("?"));

    private static String basePath = RuoYiConfig.getBackupUrl();

    private static String mysqlPath = RuoYiConfig.getMysqlPath();

    private static String dbHost = RuoYiConfig.getMysqlUrl();
//    private static String dbHost = simplify.split(":")[0];

    private static String port = RuoYiConfig.getMysqlPort();
//    private static String port = simplify.split(":")[1].split("/")[0];

    private static String dbUser = RuoYiConfig.getMysqlUsername();
//    private static String dbUser = username;

    private static String dbPwd = RuoYiConfig.getMysqlPassword();
//    private static String dbPwd = password;

    private static String dbName = RuoYiConfig.getDBName();
//    private static String dbName = simplify.split(":")[1].split("/")[1];

    private static String dateFormat = "yyyy-MM-dd-HH-mm-ss";
    // 最多保留文件数
    private static int saveFileMax = 10;
    //文件格式
    private static String fileFormat = "_" + dbName + ".sql";


    public static Date getTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 2);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 00);
        Date time = calendar.getTime();

        return time;
    }
    /**
     * @description Java代码实现MySQL数据库导出
     *
     * @author zzw
     * @param tables 需要导出的表
     * @return 返回true表示导出成功，否则返回false。
     */
    public static String exportDatabaseTool(String tables) throws InterruptedException {

        String fileName = new SimpleDateFormat(dateFormat).format(new Date()) + "_" + System.currentTimeMillis() + fileFormat;
        File saveFile = new File(basePath);
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        String savePath = basePath;
        if(!savePath.endsWith(File.separator)){
            savePath = savePath + File.separator;
        }
        PrintWriter pw = null;
        BufferedReader bufferedReader = null;
        try {
            String cmd1 = "/bin/sh";
            String cmd2 = "-c";
            String os_name = System.getProperty("os.name");
            // 判断是否是windows系统
            if (os_name.toLowerCase().startsWith("win")){
                cmd1 = "cmd";
                cmd2 = "/c";
            }
            String stmt = mysqlPath + "mysqldump -h " + dbHost + " -P" + port + " -u"
                    + dbUser + " -p" + dbPwd + " --default-character-set=utf8 -t " + dbName
                    + (StringUtils.isNotBlank(tables) ? " --tables " + tables : "")
                    + " >" + savePath + fileName;
            System.out.println(stmt);
            String[] cmd = { cmd1, cmd2 , stmt };
            Runtime.getRuntime().exec(cmd);
            return savePath + fileName;

        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (pw != null) {
                    pw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 用来恢复数据库
     * @param filepath 数据库备份的脚本路径
     * @return
     */
    public static boolean recover(String filepath) throws IOException {

//        filepath = "D:/test/test3.sql";

        String cmd1 = "/bin/sh";
        String cmd2 = "-c";
        String os_name = System.getProperty("os.name");
        // 判断是否是windows系统
        if (os_name.toLowerCase().startsWith("win")){
            cmd1 = "cmd";
            cmd2 = "/c";
        }
        String stmt2 = mysqlPath + "mysql -h " + dbHost + " -P" + port + " -u"
                + dbUser + " -p" + dbPwd + " --default-character-set=utf8 -t " + dbName
                + " <" + filepath;
        String[] cmd = { cmd1, cmd2, stmt2 };
        try {
            System.out.println(cmd[2]);
            Runtime.getRuntime().exec(cmd);
            System.out.println("数据已从 " + filepath + " 导入到数据库中");
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除文件夹中最早产生的一个文件，如csv文件夹永远只保留max=30个最新的文件，超过30则删除一个文件
     * 注意：是根据文件命名来delete的，所以必须要有公共的命名规则
     *
     * @param commonFileSuffix 文件夹下的文件名的公共后缀：如_log.txt
     * @param fileDir          文件夹名称
     * @param max              文件夹下最多的文件数量
     * @param format           时间格式
     */
    public static void deleteFurthestFile(String fileDir, String format, final String commonFileSuffix, final int max) {
        try {
            File dir = new File(fileDir);
            if (!dir.exists()) {
                return;
            }
            int currentNum = 0;
            if (dir.exists()) {
                File[] youxiaoFile = dir.listFiles(new FileFilter() {
                    public boolean accept(File pathname) {
                        return pathname.getName().endsWith(fileFormat);
                    }
                });

                currentNum = youxiaoFile.length;  //得到当前文件夹文件数目
            }

            if (currentNum > max) {
                do {
                    //得到文件名的一个map
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
                    Map<Long, String> map = new HashMap();
                    for (File file1 : dir.listFiles()) {
                        if (file1.getName().startsWith(".")) {
                            continue;
                        }
                        String time = file1.getName().replace(commonFileSuffix, "");
                        try {
                            Date date = simpleDateFormat.parse(time);
                            map.put(date.getTime(), file1.getName()); //<1233282716409,2018-2-1_log.txt>
                        } catch (RuntimeException e) {
                            System.out.println(" file:" + file1.getName());
                        }
                    }

                    //产生时间最早的文件名
                    long lt = Long.valueOf(Collections.min(map.keySet()).toString());
                    File f1 = new File(fileDir + File.separator + map.get(lt));
                    if (f1.exists()) {
                        System.out.println(" delete file:" + f1.getName());
                        f1.delete();
                        currentNum--;
                    }
                } while (currentNum > max);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


}